package com.breeze.components.mybatis.page;

import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.Data;

/**
 * 如果是简单的排序 和 时间范围筛选 可以使用内置的这几个字段
 *
 * @author breeze
 */
@Data
public abstract class AbstractQuery {

  private static final String ASC = "ascending";
  private static final String DESC = "descending";
  protected String orderColumn;
  protected String orderDirection;
  protected String timeRangeColumn;
  Integer startTime;
  Integer endTime;

  public QueryWrapper toQueryWrapper() {
    return new QueryWrapper();
  }

  public abstract QueryWrapper addQueryCondition();

  public void addSortCondition(QueryWrapper queryWrapper) {
    if (queryWrapper == null || StrUtil.isEmpty(orderColumn)) {
      return;
    }

    Boolean sortDirection = convertSortDirection();
    if (sortDirection != null && StrUtil.isNotEmpty(orderColumn)) {
      queryWrapper.orderBy(StrUtil.toUnderlineCase(orderColumn), sortDirection);
    }
  }

  /**
   * 获取前端传来的排序方向 转换成MyBatisPlus所需的排序参数 boolean=isAsc
   *
   * @return 排序顺序， null为无排序
   */
  public Boolean convertSortDirection() {
    Boolean isAsc = null;
    if (StrUtil.isEmpty(this.orderDirection)) {
      return isAsc;
    }

    if (ASC.equals(this.orderDirection)) {
      isAsc = true;
    }
    if (DESC.equals(this.orderDirection)) {
      isAsc = false;
    }

    return isAsc;
  }
}
